package com.codeanalysissys.backend.enums;

import com.codeanalysissys.backend.entity.LanguageEnum;
import org.springframework.core.convert.converter.Converter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class LangToEnumConverter <T extends LanguageEnum> implements Converter<String, T> {
    private final Map<String, T> langEnumMAP = new HashMap<>();

    public LangToEnumConverter(Class<T> enumType) {
        Arrays.stream(enumType.getEnumConstants())
                .forEach(x -> {
                    langEnumMAP.put(x.getName(), x);
                });
    }

    @Override
    public T convert(String source) {
        return Optional.of(source)
                .map(langEnumMAP::get)
                .orElseThrow(RuntimeException::new);
    }
}
